package com.hqbzl.c1.rlock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class Test2 {
    final static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        final Thread thread = new Thread(() -> {
            try {
                log.debug("尝试获取锁");
                if (!lock.tryLock(5, TimeUnit.SECONDS)) {
                    log.debug("没获取到锁");
                    return;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                return;
            }
            try {
                log.debug("doWork");
            } finally {
                lock.unlock();
            }
        }, "t1");
        log.debug("主线程加锁");
        lock.lock();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.start();
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.debug("主线程释放锁");
        lock.unlock();
    }

}
